package com.icesoft.core.web.configurer;

import com.icesoft.core.web.configurer.filter.AdminServerIpHelper;
import com.icesoft.core.web.configurer.filter.HttpHostHeaderFilter;
import com.icesoft.core.web.configurer.filter.IpPathFilter;
import com.icesoft.core.web.suppose.safehttp.filter.SafeRequestCryptoService;
import com.icesoft.core.web.suppose.safehttp.request.RequestSettingFilter;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

//通过FilterRegistrationBean实例设置优先级可以生效
// 通过@WebFilter无效
@Configuration
public class FilterBeanConfig {

    @Bean
    @ConditionalOnProperty(name = "icesoft.safe.host-path")
    public FilterRegistrationBean<HttpHostHeaderFilter> httpHostHeaderFilter(IcesoftSafeProperty safeProperty) {
        FilterRegistrationBean<HttpHostHeaderFilter> bean = new FilterRegistrationBean<HttpHostHeaderFilter>();
        bean.setFilter(new HttpHostHeaderFilter(safeProperty));// 注册自定义过滤器
        bean.setName("httpHostHeaderFilter");// 过滤器名称
        bean.addUrlPatterns("/*");// 过滤所有路径
        bean.setOrder(1);// 优先级，1最顶级
        return bean;
    }

    @Bean
    public FilterRegistrationBean<RequestSettingFilter> requestSettingFilter(SafeRequestCryptoService safeRequestCryptoService) {
        FilterRegistrationBean<RequestSettingFilter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new RequestSettingFilter(safeRequestCryptoService));// 注册自定义过滤器
        bean.setName("requestSettingFilter");// 过滤器名称
        bean.addUrlPatterns("/*");// 过滤所有路径
        bean.setOrder(2);
        return bean;
    }

    @Bean
    @ConditionalOnProperty(name = "management.endpoints.web.base-path", havingValue = "/whiteIp/actuator")
    public FilterRegistrationBean<IpPathFilter> ipPathFilter(IcesoftSafeProperty icesoftSafeProperty, ObjectProvider<AdminServerIpHelper> adminServerIpHelperObjectProvider) {
        FilterRegistrationBean<IpPathFilter> bean = new FilterRegistrationBean<IpPathFilter>();
        bean.setFilter(new IpPathFilter(icesoftSafeProperty.getWhiteIp(), adminServerIpHelperObjectProvider.getIfAvailable()));// 注册自定义过滤器
        bean.setName("ipPathFilter");// 过滤器名称
        bean.addUrlPatterns("/whiteIp/*");// 过滤所有路径
        bean.setOrder(2);
        return bean;
    }

}
